class SportsmanController {

    def index = {}
    def error = {}
    def edit = {
    	if (params.pw != "2oo9") { 
    		flash.message = "You can't pass!!"
    		redirect(action:error)
    	}
    	
    	[people:searchPeople()]
    }
    
    def singleEdit = {
    	def person = Sportsman.get(params.id)
    	[person:person]
    }
    
    def singleUpdate = {
    	def person = Sportsman.get(params.id) 
    	if (person) {
    		person.properties = params
	    	if (person.save()) {
		    	if (params.oriUid != params.uid) {
		    		(new History([person:person, fieldName:'認證號碼', beforeValue:(params.oriUid)?params.oriUid:"", afterValue:params.uid])).save()
		    	}
		    	if (params.oriName != params.name) {
		    		(new History([person:person, fieldName:'姓名', beforeValue:(params.oriName)?params.oriName:"", afterValue:params.name])).save()
		    	}
		    	if (params.oriSurname != params.surname) {
		    		(new History([person:person, fieldName:'surname', beforeValue:(params.oriSurname)?params.oriSurname:"", afterValue:params.surname])).save()
		    	}
		    	if (params.oriSport != params.sport.id) {
		    		def oriSportIns = null
		    		if (params.oriSport) {
		    			oriSportIns = Sport.get(params.oriSport)
		    		}
		    		def sportIns = Sport.get(params.sport.id)
		    		(new History([person:person, fieldName:'運動項目', beforeValue:(oriSportIns)?oriSportIns.name:"", afterValue:sportIns.name])).save()
		    	}
		    	if (params.oriNation != params.nation.id) {
		    		def oriNationIns = null
		    		if (params.oriNation){
		    			oriNationIns = Nation.get(params.oriNation)
		    		}
		    		def nationIns = Nation.get(params.nation.id)
		    		(new History([person:person, fieldName:'國別', beforeValue:(oriNationIns)?oriNationIns.name:"", afterValue:nationIns.name])).save()
		    	}
		    	if (params.oriHotel != params.hotel) {
		    		(new History([person:person, fieldName:'旅館', beforeValue:(params.oriHotel)?params.oriHotel:"", afterValue:params.hotel])).save()
		    	}
		    	if (params.oriSex != params.sex) {
		    		(new History([person:person, fieldName:'性別', beforeValue:(params.oriSex)?params.oriSex:"", afterValue:params.sex])).save()
		    	}
		    	if (params.oriCategory != params.category) {
		    		(new History([person:person, fieldName:'category', beforeValue:(params.oriCategory)?params.oriCategory:"", afterValue:params.category])).save()
		    	}
		    	if ((params.oriComeDateAt_year != params.comeDateAt_year) ||
		    		(params.oriComeDateAt_month != params.comeDateAt_month) ||
		    		(params.oriComeDateAt_day != params.comeDateAt_day) ||
		    		(params.oriComeDateAt_hour != params.comeDateAt_hour) ||
		    		(params.oriComeDateAt_minute != params.comeDateAt_minute)
		    		) {
		    		def calendar = Calendar.getInstance()
		    		
		    		calendar.set((params.oriComeDateAt_year)?params.oriComeDateAt_year.toInteger():1970, 
			    				(params.oriComeDateAt_month)?params.oriComeDateAt_month.toInteger()-1:0,
	    						(params.oriComeDateAt_day)?params.oriComeDateAt_day.toInteger():0, 
								(params.oriComeDateAt_hour)?params.oriComeDateAt_hour.toInteger():0, 
								(params.oriComeDateAt_minute)?params.oriComeDateAt_minute.toInteger():0)
		    		def oriComeDate = calendar.getTime()
		    		
		    		calendar.set(params.comeDateAt_year.toInteger(), 
		    				     params.comeDateAt_month.toInteger()-1, 
		    				     params.comeDateAt_day.toInteger(), 
		    				     params.comeDateAt_hour.toInteger(), 
		    				     params.comeDateAt_minute.toInteger())
		    		def comeDate = calendar.getTime()
		    		
		    		(new History([person:person, fieldName:'預計抵達時間', beforeValue:(oriComeDate > new Date(0))?oriComeDate.format("yyyy-MM-dd HH:mm"):"", afterValue:comeDate.format("yyyy-MM-dd HH:mm")])).save()
		    	}
		    	if (params.oriComeFlight != params.comeFlight) {
		    		(new History([person:person, fieldName:'抵達班機', beforeValue:(params.oriComeFlight)?params.oriComeFlight:"", afterValue:params.comeFlight])).save()
		    	}
		    	if (params.oriComeAirport != params.comeAirport.id) {
		    		def oriComeAirportIns = null
		    		if (params.oriComeAirport) {
		    			oriComeAirportIns = Airport.get(params.oriComeAirport)
		    		}
		    		def comeAirportIns = Airport.get(params.comeAirport.id)
		    		(new History([person:person, fieldName:'抵達機場', beforeValue:(oriComeAirportIns)?oriComeAirportIns.name:"", afterValue:comeAirportIns.name])).save()
		    	}
		    	if ((params.oriGoDateAt_year != params.goDateAt_year) ||
		    		(params.oriGoDateAt_month != params.goDateAt_month) ||
		    		(params.oriGoDateAt_day != params.goDateAt_day) ||
		    		(params.oriGoDateAt_hour != params.goDateAt_hour) ||
		    		(params.oriGoDateAt_minute != params.goDateAt_minute)
		    		) {
		    		def calendar = Calendar.getInstance()
		    		
		    		calendar.set((params.oriGoDateAt_year)?params.oriGoDateAt_year.toInteger():1970, 
			    				(params.oriGoDateAt_month)?params.oriGoDateAt_month.toInteger()-1:0,
	    						(params.oriGoDateAt_day)?params.oriGoDateAt_day.toInteger():0, 
								(params.oriGoDateAt_hour)?params.oriGoDateAt_hour.toInteger():0, 
								(params.oriGoDateAt_minute)?params.oriGoDateAt_minute.toInteger():0)
		    		def oriGoDate = calendar.getTime()
		    		
		    		calendar.set(params.goDateAt_year.toInteger(), 
		    				     params.goDateAt_month.toInteger()-1, 
		    				     params.goDateAt_day.toInteger(), 
		    				     params.goDateAt_hour.toInteger(), 
		    				     params.goDateAt_minute.toInteger())
		    		def goDate = calendar.getTime()
		    		
		    		(new History([person:person, fieldName:'預計離開時間', beforeValue:(oriGoDate > new Date(0))?oriGoDate.format("yyyy-MM-dd HH:mm"):"", afterValue:goDate.format("yyyy-MM-dd HH:mm")])).save()
		    	}
		    	if (params.oriGoFlight != params.goFlight) {
		    		(new History([person:person, fieldName:'離開班機', beforeValue:(params.oriGoFlight)?params.oriGoFlight:"", afterValue:params.goFlight])).save()
		    	}
		    	if (params.oriGoAirport != params.goAirport.id) {
		    		def oriGoAirportIns = null
		    		if (params.oriGoAirport) {
		    			oriGoAirportIns = Airport.get(params.oriGoAirport)
		    		}
		    		def goAirportIns = Airport.get(params.goAirport.id)
		    		(new History([person:person, fieldName:'離開機場', beforeValue:(oriGoAirportIns)?oriGoAirportIns.name:"", afterValue:goAirportIns.name])).save()
		    	}
		    	if (params.oriNote != params.note) {
		    		(new History([person:person, fieldName:'備註', beforeValue:(params.oriNote)?params.oriNote:"", afterValue:params.note])).save()
		    	}
	    	}
    	}
    	redirect(action:singleEdit, params:[id:person.id])
    }
    
    def history = {
    		[histories:History.list(sort:'createdDate', order:'desc')]
    }
    
    def search = {
    	[people:searchPeople()]
    }
    
    def searchSubmit = {
    	def people = Sportsman.findAllByNameLike('%'+ params.searchKey +'%')
    	[people:people]
    }
    
    def show = {
		def person = Sportsman.get( params.id )

        if(!person) {
            flash.message = "Sportsman does not found with id ${params.id}"
            redirect(action:search)
        }
		
		def histories = History.findAllByPerson(person, [sort:'createdDate', order:'desc'])
        [person : person, histories:histories]
    }
    
    def create = {
		def person = new Sportsman()
		person.properties = params
        [personInstance:person]
    }
    
    def save = {
        	def sport = Sport.get(params.sport.id)
        	def nation = Nation.get(params.nation.id)
        	
        	def personInstance = new Sportsman(params)
            if(!personInstance.hasErrors() && personInstance.save()) {
                flash.message = "Person ${personInstance.name} created"
                redirect(action:show,id:personInstance.id)
            }
            else {
                render(view:'create',model:[personInstance:personInstance])
            }
    }
    def upload = {}
    def uploadSubmit = {
    	def file = request.getFile('sportsman')
    	if (file) {
    		def inputStream = file.getInputStream()
    		if (inputStream){
    			def br = new BufferedReader(new InputStreamReader(inputStream))
    			def line = br.readLine()
    			def key = line.split(',')
    			
    			def personCount = 0
    			while ((line = br.readLine()) != null) {
    				def tokens = line.split(',')
    				def entity = [:]
    				for (def i = 0; i < tokens.size(); i++) {
    					entity[key[i]] = tokens[i]
    				}
    				//save person
    				def person = Sportsman.findByUid(entity['uid'])
    				def sport = Sport.findByName(entity['sport'])
    				def nation = Nation.findByName(entity['nation'])
    				
    				def comeAirport = null
    				if (entity['comeAirport']) {
    					comeAirport = Airport.findByName(entity['comeAirport']) 
    				}
    				
    				def goAirport = null
    				if (entity['goAirport']) {
    					goAirport = Airport.findByName(entity['goAirport']) 
    				}

    				// come date 
    				def comeDateAt = null
    				if (entity['comeDateAt'] && entity['comeTimeAt']) {
    					def dateTokens = entity['comeDateAt'].split('/')
    					def timeTokens = entity['comeTimeAt'].split(':')
    					def yearInt = (dateTokens[0].toInteger())
    					def monthInt = null
    					if (dateTokens[1].toInteger()) {
    						monthInt = (dateTokens[1].toInteger()) - 1
    					}
    					if (!dateTokens[2].contains('-') && timeTokens.size() > 1 && !timeTokens[0].contains('-') && !timeTokens[0].contains('m') && !timeTokens[1].contains('-') && !timeTokens[1].contains('m')) {
    						def calendar = Calendar.getInstance();
    						calendar.set(yearInt, monthInt, dateTokens[2].toInteger(), timeTokens[0].toInteger(), timeTokens[1].toInteger())
    						comeDateAt = calendar.getTime()
    					}
    				}
    				
    				// go date
    				def goDateAt = null
    				if (entity['goDateAt'] && entity['goTimeAt']) {
    					def dateTokens = entity['goDateAt'].split('/')
    					def timeTokens = entity['goTimeAt'].split(':')
    					def yearInt = (dateTokens[0].toInteger())
    					def monthInt = null
    					if (dateTokens[1].toInteger()) {
    						monthInt = (dateTokens[1].toInteger()) - 1
    					}
    					if (!dateTokens[2].contains('-') && timeTokens.size() > 1 && !timeTokens[0].contains('-') && !timeTokens[0].contains('m') && !timeTokens[0].contains('M') && !timeTokens[1].contains('-') && !timeTokens[1].contains('m') && !timeTokens[1].contains('M')) {
    						def calendar = Calendar.getInstance();
    						calendar.set(yearInt, monthInt, dateTokens[2].toInteger(), timeTokens[0].toInteger(), timeTokens[1].toInteger())
    						goDateAt = calendar.getTime()
    					}
    				}
    				
    				if (!person) {
    					person = new Sportsman([uid:entity['uid'],
    					                        name:entity['name'], 
    					                        surname:entity['surname'],
    					                        sex:entity['sex'],
    					                        category:entity['category'],
    					                        hotel:entity['hotel'],
    					                        sport:sport,
    					                        nation:nation,
    					                        comeAirport:comeAirport,
    					                        goAirport:goAirport,
    					                        comeFlight:entity['comeFlight'],
    					                        goFlight:entity['goFlight'],
    					                        comeDateAt:comeDateAt,
    					                        goDateAt:goDateAt
    					])
    				}
    				if(person.save()) {
    					personCount++
    				}
    			}
   				flash.message = personCount + '筆資料上傳成功 '
    		}
    	}
    	redirect(action:upload)
    }
    
    //  methods ------------------
    def searchPeople() {
    	def people = []	
    	if (params.searchType == "name") {
    		people = Sportsman.findAllByNameLike('%'+ params.searchKey +'%',[sort:"comeDateAt"])
    	} else if (params.searchType == "uid") {
    		people = Sportsman.findAllByUidLike('%'+ params.searchKey +'%',[sort:"comeDateAt"])
    	} else if (params.searchType == "nation") {
    		def nation = Nation.get(params.searchKey)
    		people = Sportsman.findAllByNation(nation,[sort:"comeDateAt"])
    	} else if (params.searchType == "sport") {
    		def sport = Sport.get(params.searchKey)
    		people = Sportsman.findAllBySport(sport,[sort:"comeDateAt"])
    	} else if (params.searchType == "comeDate") {
    		def calendar = Calendar.getInstance()
    		calendar.set(params.startAt_year.toInteger(), params.startAt_month.toInteger()-1, params.startAt_day.toInteger(), params.startAt_hour.toInteger(), params.startAt_minute.toInteger())
    		def start = calendar.getTime()
    		
    		calendar.set(params.endAt_year.toInteger(), params.endAt_month.toInteger()-1, params.endAt_day.toInteger(), params.endAt_hour.toInteger(), params.endAt_minute.toInteger())
    		def end = calendar.getTime()
    		
			people = Sportsman.findAll("from Sportsman as s where s.comeDateAt > ? and s.comeDateAt < ?", [start, end]);
    	} else if (params.searchType == "goDate") {
    		def calendar = Calendar.getInstance()
    		calendar.set(params.startAt_year.toInteger(), params.startAt_month.toInteger()-1, params.startAt_day.toInteger(), params.startAt_hour.toInteger(), params.startAt_minute.toInteger())
    		def start = calendar.getTime()
    		
    		calendar.set(params.endAt_year.toInteger(), params.endAt_month.toInteger()-1, params.endAt_day.toInteger(), params.endAt_hour.toInteger(), params.endAt_minute.toInteger())
    		def end = calendar.getTime()
    		
			people = Sportsman.findAll("from Sportsman as s where s.goDateAt > ? and s.goDateAt < ?", [start, end]);
    	} else if (params.searchType == "today") {
    		def today = Calendar.getInstance()
    		today.set(Calendar.HOUR_OF_DAY, 0)
    		today.set(Calendar.MINUTE, 0)
    		def start = today.getTime()
    		
    		today = Calendar.getInstance()
    		today.set(Calendar.HOUR_OF_DAY, 23)
    		today.set(Calendar.MINUTE, 59)
    		def end = today.getTime()
    		
			people = Sportsman.findAll("from Sportsman as s where s.comeDateAt > ? and s.comeDateAt < ?", [start, end]);
	    } else if (params.searchType == "arrivalPeople") {
			def calendar = Calendar.getInstance()
			calendar.set(params.startAt_year.toInteger(), params.startAt_month.toInteger()-1, params.startAt_day.toInteger(), params.startAt_hour.toInteger(), params.startAt_minute.toInteger())
			def start = calendar.getTime()
			
			calendar.set(params.endAt_year.toInteger(), params.endAt_month.toInteger()-1, params.endAt_day.toInteger(), params.endAt_hour.toInteger(), params.endAt_minute.toInteger())
			def end = calendar.getTime()
			
			def query = null
			if (params.point == '桃園機場') {
				query = 'nAirportComeAt' 
			} else if (params.point == '桃園高鐵') {
				query = 'nTrainComeAt'
			} else if (params.point == '左營高鐵') {
				query = 'sTrainComeAt'
			} else if (params.point == '認證中心') {
				query = 'centerComeAt'
			} else if (params.point == '旅館') {
				query = 'hotelComeAt'
			}
			people = Sportsman.findAll("from Sportsman as s where s."+ query + "> ? and s."+ query +" < ?", [start, end]);
		}
    	return people
    }
}
